// socket已经连接成功
var socketOpen = false
// socket已经调用关闭function
var socketClose = false
// socket发送的消息队列
var socketMsgQueue = []
// 判断心跳变量
var heart = ''
// 心跳失败次数
var heartBeatFailCount = 0
// 终止心跳
var heartBeatTimeOut = null;
// 终止重新连接
var connectSocketTimeOut = null;
var i = 1
const url = '' //socket链接地址，需要在微信后台配置
var webSocket = {
    wss: null,
    guid: '',
    connectSocket: function () {
        socketOpen = false
        socketClose = false
        var self = this;
        self.wss = new WebSocket('wss://saasyy.com:30100/');
        // 监听WebSocket连接打开事件。callback 回调函数
        webSocket.wss.onopen = function (e) {
            console.log('WebSocket连接已打开！')
            socketOpen = true;
            console.log(socketMsgQueue.length);
            setTimeout(function () {
                for (var i = 0; i < socketMsgQueue.length; i++) {
                    webSocket.sendSocketMessage(socketMsgQueue[i])
                }
                socketMsgQueue = []
            }, 5000)
            webSocket.startHeartBeat();
        }

        // 监听WebSocket错误。
        webSocket.wss.onerror = function () {
            console.log('WebSocket连接打开失败，请检查！', res)
            if (heartBeatFailCount > 2) {
                // 重连
                self.connectSocket();
            }
            if (heart) {
                if (heartBeatTimeOut) {
                    clearTimeout(heartBeatTimeOut);
                    heartBeatTimeOut = null;
                }
                heartBeatTimeOut = setTimeout(() => {
                    self.heartBeat();
                }, 60000);
            }
            heartBeatFailCount++;
        }

        // 监听WebSocket接受到服务器的消息事件。
        webSocket.wss.onmessage = function (e) {
            webSocket.onSocketMessageCallback(e.data)
        }

        // 监听WebSocket关闭。
        webSocket.wss.onclose = function (e) {
            console.log('WebSocket 已关闭!');
            socketClose = true;
            //if (!socketClose) {
            let time = Math.pow(2, i)
            i++
            if (time == 8) {
                i = 1
            }
            clearTimeout(connectSocketTimeOut)
            connectSocketTimeOut = setTimeout(() => {
                webSocket.connectSocket();
            }, time * 1000);

            if (connectSocketTimeOut) {
                clearTimeout(connectSocketTimeOut);
                connectSocketTimeOut = null;
            }
            socketClose = true;
            var self = this;
            self.stopHeartBeat();
        }
    },
    /**
     * 通过 WebSocket 连接发送数据
     */
    sendSocketMessage: function (options) {
        var self = this;
        if (socketOpen) {
            self.wss.send(JSON.stringify(options.msg));
            if (options) {
                options.success && options.success();
            }
        } else {
            socketMsgQueue.push(options)
        }
    },
    /**
     * 关闭 WebSocket 连接。
     */
    closeSocket: function (options) {
        if (connectSocketTimeOut) {
            clearTimeout(connectSocketTimeOut);
            connectSocketTimeOut = null;
        }
        socketClose = true;
        var self = this;
        self.stopHeartBeat();
        // this.wss.close();
    },
    // 收到消息回调
    onSocketMessageCallback: function (msg) {

    },

    // 开始心跳
    startHeartBeat: function () {
        console.log('socket开始心跳')
        var self = this;
        heart = 'heart';
        self.heartBeat();
    },

    // 结束心跳
    stopHeartBeat: function () {
        console.log('socket结束心跳')
        var self = this;
        heart = '';
        if (heartBeatTimeOut) {
            clearTimeout(heartBeatTimeOut);
            heartBeatTimeOut = null;
        }
        if (connectSocketTimeOut) {
            clearTimeout(connectSocketTimeOut);
            connectSocketTimeOut = null;
        }
    },

    // 心跳
    heartBeat: function () {
        var self = this;
        if (!heart) {
            return;
        }
        self.sendSocketMessage({
            msg: {
                messageType: 1, //心跳
                guid: this.guid
            },
            success: function () {
                console.log('socket心跳成功');
                if (heart) {
                    heartBeatTimeOut = setTimeout(() => {
                        self.heartBeat();
                    }, 60000);
                }
            }
        });
    }
}

